//配置路由
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";
//vuerouter是一个插件，需要用vue.use()使用插件
Vue.use(VueRouter);
//二次封装$router.push
let orgPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    orgPush.call(this, location, resolve, reject);
  } else {
    orgPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
//二次封装$router.replace
let orgReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    orgReplace.call(this, location, resolve, reject);
  } else {
    orgReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};

let router = new VueRouter({
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { x: 0, y: 0 };
  },
});
//全局前置守卫：
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token;
  let name = store.state.user.userInfo.name;
  if (token) {
    //用户已登录
    if (to.path == "/login") {
      next("/");
    } else {
      if (name) {
        next();
      } else {
        try {
          //获取用户信息
          await store.dispatch("getUserInfo");
          next();
        } catch (error) {
          //token过期了
          //应该清除token，并重新登录
          await store.dispatch("userLogout");
          next("/login");
        }
      }
    }
  } else {
    //未登录,不能去支付相关、交易相关、个人中心
    let toPath = to.path;
    if (
      toPath.indexOf("/trade") != -1 ||
      toPath.indexOf("/pay") != -1 ||
      toPath.indexOf("/center") != -1
    ) {
      //把未登录时想去而没有去成的信息存储于query中
      next("/login?redirect=" + toPath);
    } else {
      next();
    }
  }
});
export default router;
